package chapter04

import scala.collection.mutable

/**
 * @program lu-scala01 
 * @description:  map合并
 * @author: zhanglu 
 * @create: 2022-04-09 15:00:00
 */
object Lu15_MergedMap {

  def main(args: Array[String]): Unit = {
    val m1 = mutable.Map("a" -> 1, "b" -> 3, "c" -> 6)
    val m2 = mutable.Map("a" -> 6, "b" -> 2, "c" -> 9, "d" -> 3)

    //相同key时，后面的覆盖前面的
    println(m1 ++ m2)

    //相同key，值相加
    m1.foldLeft(m2)((mergedMap, kv) => {
      val k = kv._1
      val v = kv._2
      mergedMap(k) = mergedMap.getOrElse(k, 0) + v
      mergedMap
    })
    println(m2)


  }

}
